package com.ntd.study.base.thread;

import cn.hutool.core.lang.Console;
import lombok.SneakyThrows;

/**
 * sleep or wait 让程序等待运行
 * sleep：Thread的方法，不会释放锁，在任何地方使用
 * wait：Object的方法，会释放锁，只能在同步方代码中使用
 */
public class DemoThreadSleepOrWait {
    private static Object lock = new Object();

    static class Thread1 implements Runnable {
        @SneakyThrows
        @Override
        public void run() {
            Thread.sleep(1000);
            Console.log("线程1进入");
            synchronized (lock) {
                Console.log("线程1 sleep - 持有锁 - 其他线程等待拿到锁");
                Thread.sleep(5000);
                Console.log("线程1执行");
            }
        }
    }

    static class Thread2 implements Runnable {
        @SneakyThrows
        @Override
        public void run() {
            Console.log("线程2进入");
            synchronized (lock) {
                Console.log("线程2 wait - 释放锁 - 其他线程可以拿到锁");
                lock.wait(5000);
                Console.log("线程2执行");
            }
        }
    }

    static class Thread3 implements Runnable {
        @SneakyThrows
        @Override
        public void run() {
            Thread.sleep(2000);
            Console.log("线程3进入");
            synchronized (lock) {
                Console.log("线程3执行");
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new Thread1()).start();
        new Thread(new Thread2()).start();
        new Thread(new Thread3()).start();
    }
}
